package bhbt.controller.member.info;


import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import bhbt.controller.core.BaseController;
import bhbt.model.Member;
import bhbt.model.Message;
import bhbt.model.MessageReply;
import bhbt.service.MessageReplyService;
import bhbt.service.MessageService;
import bhbt.taglib.pagetag.Pagination;
import bhbt.utils.ContextUtil;
import bhbt.utils.CryptUtil;
import bhbt.utils.FileUtils;
import bhbt.utils.MapUtil;
import bhbt.utils.SysConst;
import bhbt.utils.Tools;






/**
 * Created by Administrator on 2016/3/25.
 */
@Controller

public class MessageController extends BaseController {
    @Resource
    private MessageService messageService;
    @Resource
    private MessageReplyService messageReplyService;
   
    
    @RequestMapping("member/info/messageList.shtml")
    public String list(HttpServletRequest request) throws Exception{
        HashMap formMap = getParameterMap(request);
        Member member = ContextUtil.getMember();
        formMap.put("memberLoginName", member.getLoginName());	
        formMap.put("pagination.orderBy"," a.id desc");  //排列
        Pagination page = messageService.queryForPageList("messageForPage",formMap);
        request.setAttribute(Pagination.pageBeanName, page);
        return "member/info/messageList";
    }
    
    @RequestMapping("member/info/messageAddShow.shtml")
    public String messageAddShow(HttpServletRequest request) throws Exception{
        
        return "member/info/messageAdd";
    }

    @RequestMapping("member/info/messageAdd.shtml")
    public String add(@RequestParam MultipartFile file, ModelMap model,HttpServletRequest request, HttpServletResponse response) throws Exception{
    	 
    	Member member = ContextUtil.getMember();
    	Map formMap = getParameterMap(request);
    	
    	String twoPassword = MapUtil.getString(formMap, "twoPassword");
    	
    	String pwd = CryptUtil.getInstance().encrypt2String(twoPassword,CryptUtil.keyStr);
    	 
    	if(!member.getTwoPassword().equals(pwd)){
    		setMessage(model,"安全密码不正确。");
    		 
    		return "member/info/messageAdd";
    		
    	}else {
    		
    		
    		try{
    			//新增
            	String title = MapUtil.getString(formMap, "title");
            	String content = MapUtil.getString(formMap, "content");
            	 
        		if(file.getOriginalFilename()==null||file.getOriginalFilename()==""){
        			
        			Message message = new Message();
        			message.setTitle(title);
        			message.setContent(content);
                    message.setMemberId(member.getId());
                    messageService.saveOrUpdate(message);
                    
                    
                    return "redirect:messageList.shtml";
        		}else{
        			
        			
                	
        			String docType = "message"; //保存的文件夹名称
                	
                	String fileName = file.getOriginalFilename();
                	String docName =  FileUtils.getUUIDFileName(fileName);
                	//复制保存到E盘
                    String newFile = SysConst.APP_FILES + docName;
                    
                    
                    String fileContentType=file.getContentType();
                    //后缀名
        			String ext = fileName.substring(fileName.lastIndexOf('.')+1).toLowerCase();
        		
        			List<String> arrowType = Arrays.asList("images/gif","images/jpg","images/jpeg","images/pjpeg","images/png","images/bmp","image/gif","image/jpg","image/jpeg","image/pjpeg","image/png","image/bmp","image/x-png");
        			List<String> arrowExt = Arrays.asList("gif","jpg","jpeg","png","bmp");
        			
        			 
        			if(!(arrowType.contains(fileContentType.toLowerCase()) && arrowExt.contains(ext))){
        				 
        				setMessage(model,"上传文件只接收gif/jpg/jpeg/png/bmp类型,您的文件类型为！"+fileContentType);
   	        		 
    	        		 
    	                return "member/info/messageAdd";
        			}else{
        				
        				if(file.getSize()>(4*1024*1024)){
        					
        					setMessage(model,"上传图片不能大于4M。");
          	        		return "member/info/messageAdd";
        				}
        				//文件存储到硬盘
                		boolean flag = FileUtils.createFileToDisk(newFile, file.getInputStream());
        				 
                        if(flag){
                            String tmpFile = Tools.getWebPath(this.getClass())+SysConst.TMP_FILE+docName;
                            FileUtils.copyFile(newFile,tmpFile);
                            //FileUtils.copyFile(newFileTomcat1,tmpFile);
                            //FileUtils.copyFile(newFileTomcat2,tmpFile);
                            
                            String path = request.getContextPath();
                        	String port = (0<request.getServerPort()) ? (":"+request.getServerPort()) : "";
                        	String basePath = request.getScheme()+"://"+request.getServerName()+port+path+"/";
                            
                           
                            Message message = new Message();
                            message.setFileName(docName);
                            message.setTitle(title);
                            //message.setFilePath(basePath+"/"+newFile);
                            message.setFilePath(basePath+SysConst.TMP_FILE);
                            message.setContent(content);
                            message.setMemberId(member.getId());
                            messageService.saveOrUpdate(message);
                            return "redirect:messageList.shtml";
                        }else{
                        	 
                        	setMessage(model,"上传图片失败");
                        	return "member/info/messageAdd";
                        }
                        
        			}
        				
        			
                    
                    
        		}
            	
        	}catch(Exception ex){
                ex.printStackTrace();
            }
		}
    	
    	
    	return "redirect:messageList.shtml";
		
     
    }
    
    @RequestMapping("member/info/messageShow.shtml")
    public String show(HttpServletRequest request) throws Exception{
        Map formMap = getParameterMap(request);
        int id = MapUtil.getIntValue(formMap, "id");
        if(0 < id){
        	Message message = messageService.getByKey(id);
        	Member member = ContextUtil.getMember();
        	if(message.getMemberId().equals(member.getId())){
        		 request.setAttribute("message",message);
                 
                 formMap.put("messageId", id);
                 List<MessageReply> list = this.messageReplyService.queryForList("messageReplyForList",formMap);
                 
                 request.setAttribute("list",list);
        	}
           
            
        }
        return "member/info/messageShow";
       
    } 
    
    
    @RequestMapping("member/info/messageShowAdd.shtml")
    public String showAdd(@RequestParam MultipartFile file, ModelMap model,HttpServletRequest request, HttpServletResponse response) throws Exception{
    	
        Map formMap = getParameterMap(request);
       
    		int id = MapUtil.getIntValue(formMap, "id");
	        if(0 < id){
	        	Member member = ContextUtil.getMember();
	        	Message message = messageService.getByKey(id);
	            String myTwoPassword = MapUtil.getString(formMap, "myTwoPassword");
	        	
	        	String pwd = CryptUtil.getInstance().encrypt2String(myTwoPassword,CryptUtil.keyStr);
	        	 
	        	if(!member.getTwoPassword().equals(pwd)){
	        		setMessage(model,"安全密码不正确。");
	        		 
	        		request.setAttribute("message",message);
	                 
	                formMap.put("messageId", id);
	                List<MessageReply> list = this.messageReplyService.queryForList("messageReplyForList",formMap);
	                 
	                request.setAttribute("list",list);
	        		return "member/info/messageShow";
	        		
	        	} else {
	        		
	        		
		        	try{
		        		//新增
	                	 
	                	String content = MapUtil.getString(formMap, "content");
	                	 
		        		if(file.getOriginalFilename()==null||file.getOriginalFilename()==""){
		        			Map mapMessage = new HashMap();
		        			mapMessage.put("id",id);
		        			mapMessage.put("type",10);
	                    	messageService.update(mapMessage);
	                    	
	                      
	                        MessageReply reply=new MessageReply();
	                		reply.setMessageId(id);			//所属服务单
	                		reply.setContent(content);			//正文
	                		reply.setType(10);					//类型(10会员回复，20管理员回复)
	                		reply.setMemberId(member.getId());			//提交会员
	                		
	                		String operIp=request.getRemoteHost();
	                		reply.setOperIp(operIp);				//提交IP
	                		reply.setOperDate(new Date());		//提交时间
	                		
	                		messageReplyService.saveOrUpdate(reply);
	                		
	                		
	                		 
	                    	if(message.getMemberId().equals(member.getId())){
	                    		 request.setAttribute("message",message);
	                             
	                             formMap.put("messageId", id);
	                             List<MessageReply> list = this.messageReplyService.queryForList("messageReplyForList",formMap);
	                             
	                             request.setAttribute("list",list);
	                    	}
	                		
	                    	return "member/info/messageShow";
	                		
		        		}else{
		        			
		        			
		                	
		                	String docType = "message"; //保存的文件夹名称
		                	
		                	String fileName = file.getOriginalFilename();
		                	String docName =  FileUtils.getUUIDFileName(fileName);
		                	String newFile = SysConst.APP_FILES + docName;
		                    //复制保存到tomcat1
		                    String newFileTomcat1 = SysConst.TOMCAT1 + docName;
		                    
		                    String fileContentType=file.getContentType();
		                    //后缀名
		        			String ext = fileName.substring(fileName.lastIndexOf('.')+1).toLowerCase();
		        		
		        			List<String> arrowType = Arrays.asList("images/gif","images/jpg","images/jpeg","images/pjpeg","images/png","images/x-png","images/bmp","image/gif","image/jpg","image/jpeg","image/pjpeg","image/png","image/bmp","image/x-png");
		        			List<String> arrowExt = Arrays.asList("gif","jpg","jpeg","png","bmp","x-png");
		        			
		        			 
		        			if(!(arrowType.contains(fileContentType.toLowerCase()) && arrowExt.contains(ext))){
		        				 
		        				setMessage(model,"上传文件只接收gif/jpg/jpeg/png/bmp类型,您的文件类型为！"+fileContentType);
		   	        		 
		    	        		request.setAttribute("message",message);
		    	                 
		    	                formMap.put("messageId", id);
		    	                List<MessageReply> list = this.messageReplyService.queryForList("messageReplyForList",formMap);
		    	                 
		    	                request.setAttribute("list",list);
		    	        		return "member/info/messageShow";
		        			}else {
		        				if(file.getSize()>(4*1024*1024)){
		        					
		        					setMessage(model,"上传图片不能大于4M。");
		        					request.setAttribute("message",message);
			    	                 
			    	                formMap.put("messageId", id);
			    	                List<MessageReply> list = this.messageReplyService.queryForList("messageReplyForList",formMap);
			    	                 
			    	                request.setAttribute("list",list);
			    	        		return "member/info/messageShow";
		        				}
		        				//文件存储到硬盘
		                		boolean flag = FileUtils.createFileToDisk(newFile, file.getInputStream());
		        				boolean flag1 = FileUtils.createFileToDisk(newFileTomcat1, file.getInputStream());
		                		
		                		String path = request.getContextPath();
	                        	String port = (0<request.getServerPort()) ? (":"+request.getServerPort()) : "";
	                        	String basePath = request.getScheme()+"://"+request.getServerName()+port+path+"/";
	                            
		                        if(flag1){
			                    	
			                    	
			                    	Map mapMessage = new HashMap();
			                    	mapMessage.put("id",id);
			                    	mapMessage.put("type",10);
			                    	messageService.update(mapMessage);
			                    	
			                        String tmpFile = Tools.getWebPath(this.getClass())+SysConst.TMP_FILE+docName;
			                        FileUtils.copyFile(newFile,tmpFile);
			                        //FileUtils.copyFile(newFileTomcat1,tmpFile);
		                            //FileUtils.copyFile(newFileTomcat2,tmpFile);
		                            
			                        MessageReply reply=new MessageReply();
			                		reply.setMessageId(id);			//所属服务单
			                		reply.setContent(content);			//正文
			                		reply.setFileName(docName);			//附件名称
			                		reply.setFilePath(basePath+SysConst.TMP_FILE);
			                		
			                		reply.setType(10);					//类型(10会员回复，20管理员回复)
			                		reply.setMemberId(member.getId());			//提交会员
			                		
			                		String operIp=request.getRemoteHost();
			                		reply.setOperIp(operIp);				//提交IP
			                		reply.setOperDate(new Date());		//提交时间
			                		
			                		messageReplyService.saveOrUpdate(reply);
			                		if(message.getMemberId().equals(member.getId())){
			                    		 request.setAttribute("message",message);
			                             
			                             formMap.put("messageId", id);
			                             List<MessageReply> list = this.messageReplyService.queryForList("messageReplyForList",formMap);
			                             
			                             request.setAttribute("list",list);
			                    	}
			                		
			                    	return "member/info/messageShow";
			                    }else{
			                    	 
			                    	setMessage(model,"上传图片失败");
			                    	request.setAttribute("message",message);
			   	                 
			    	                formMap.put("messageId", id);
			    	                List<MessageReply> list = this.messageReplyService.queryForList("messageReplyForList",formMap);
			    	                 
			    	                request.setAttribute("list",list);
			                    	return "member/info/messageShow";
			                    }
			                    
			                    
							}
		               
		                    
		        		}
		            	
		        	}catch(Exception ex){
		                ex.printStackTrace();
		            }
		        	
		            request.setAttribute("message",message);
		        
	        	}
	        	
	        	
		}
        
       
        return "member/info/messageShow";
       
    } 
}
